<template>
  <div>
    <el-dialog v-model="dialogVisible" title="批量修改" @close="handleClose">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="140px" :validate-on-rule-change="false">
        <!-- <el-form-item label="链接类型">
          <el-select v-model="curType" disabled>
            <el-option v-for="(item, key) in appTypeList" :key="key" :value="item.type" :label="item.desc"></el-option>
          </el-select>
          <div class="text-[12px] text-[#68affb] tips">目前仅支持端原生IAA</div>
        </el-form-item>
        <el-form-item label="商品名称" prop="trade_name">
          <el-input v-model="form.trade_name" placeholder="请输入商品名称" />
        </el-form-item> -->
        <el-form-item label="日预算">
          <el-input type="number" v-model="form.budget" :min="300" :max="9999999.99" placeholder="请输入日预算" />
          <div class="text-[12px] text-[#68affb] tips">预算不少于300元，不超过9999999.99元</div>
        </el-form-item>
        <el-form-item label="ROI系数">
          <el-input type="number" v-model="form.roi_goal" :min="0.01" :max="5" placeholder="请输入ROI系数" />
          <div class="text-[12px] text-[#68affb] tips">不小于0.01，不超过5,支持最多四位小数</div>
        </el-form-item>
        <el-form-item label="投放时段">
          <div class="relative inputVal" style="height: auto !important" @click="handelTimeSelect">
            {{ showSelectTimeStr ? showSelectTimeStr : '请选择投放时段' }}
            <div class="absolute right-[6px] top-[4px] cursor-pointer clear" v-if="showSelectTimeStr" @click.stop="clearTime">
              <el-icon><Close /></el-icon>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false" :loading="buttonLoading">取消</el-button>
          <el-button type="primary" @click="submit" :loading="buttonLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog v-model="showTimeSelect" title="选择投放时段">
      <TimeSelect v-if="showTimeSelect" ref="'timeSelectRef'" :needSelectText="true" @get-value="(val) => getTimeValue(val)" />
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showTimeSelect = false">取消</el-button>
          <el-button type="primary" @click="showTimeSelect = false">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { automaticPlacementIaa } from '@/api/ai';
import { IaaUpdateBatchVO } from '@/api/ai/types';
import useUserStore from '@/store/modules/user';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const props = defineProps({
  show: {
    type: Boolean,
    default: false
  },
  curRow: {
    type: Object
  }
});

const showTimeSelect = ref(false);

const selectTimeStr = ref('');

const showSelectTimeStr = ref('');

const dialogVisible = ref(false);
const emit = defineEmits(['update:visible', 'refresh']);
watch(
  () => props.show,
  (val) => {
    dialogVisible.value = val;
  },
  {
    immediate: true
  }
);
const userStore = useUserStore();

const buttonLoading = ref(false);

const formRef = ref(null);

const account = ref('');

const project = ref('');

const curType = ref('7');

const form = reactive<IaaUpdateBatchVO>({
  // library_name: '端',
  // user: userStore.nickname, //用户
  // dept_id: String(userStore.deptId), //部门id
  advertiser_id: null, //广告主id
  budget: 300, //预算
  roi_goal: 0.01 //ROI系数
});

watch(
  () => props.curRow,
  (val) => {
    nextTick(() => {
      form.advertiser_id = props.curRow.thirdAdvertiserId;
      // curType.value = props.curRow.referralLinkType.toString();
      // form.trade_name = props.curRow.dramaTitle;
    });
  }
);

const validateNumber = (rule: any, value: any, callback: any) => {
  const numValue = Number(value);

  // 检查是否为有效数字
  if (value && !/^\d+(\.\d{1,2})?$/.test(value)) {
    callback(new Error('请输入数字，最多保留两位小数'));
  } else if (numValue < 300 || numValue > 9999999.99) {
    callback(new Error('数字必须介于 300 和 9999999.99 之间'));
  } else {
    callback();
  }
};
const validateRoiNumber = (rule: any, value: any, callback: any) => {
  const numValue = Number(value);

  // 检查是否为有效数字
  if (value && !/^\d+(\.\d{1,4})?$/.test(value)) {
    callback(new Error('请输入数字，最多保留四位小数'));
  } else if (numValue < 0.01 || numValue > 5) {
    callback(new Error('数字必须介于 0.01 和 5 之间'));
  } else {
    callback();
  }
};

const rules = {
  budget: [
    { required: true, message: '请输入预算', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' }
  ],
  roi_goal: [
    { required: true, message: '请输入ROI系数', trigger: 'blur' },
    { validator: validateRoiNumber, trigger: 'blur' }
  ]
};
// 初始化函数
const resetForm = () => {
  // form.library_name = '端';
  // form.user = userStore.nickname;
  // form.dept_id = String(userStore.deptId);
  form.budget = 1000;
  form.roi_goal = 1.05;
  form.advertiser_id = null;
};
/**
 * 关闭弹窗
 */
const handleClose = () => {
  resetForm();
  emit('update:visible', false);
};

const updateInfo = async (data) => {
  try {
    const response = await fetch(import.meta.env.VITE_BASE_AI_URL + 'automatic_placement/inner/batch_update', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(data)
    });

    const result = await response.json(); // 解析 JSON 数据
    return result; // 返回结果
  } catch (err) {
    // console.log('err', err); // 捕获并输出错误
    throw err; // 可选择抛出错误以供调用时处理
  }
};

const getTimeValue = (time) => {
  selectTimeStr.value = time.str;
  showSelectTimeStr.value = time.days;
};

/**
 * 提交数据
 */
const submit = async () => {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      //   if (!account.value && !form.advertiser_num) {
      //     proxy?.$modal.msgError('账户列表与账户数量二者必填其一');
      //     return;
      //   }
      if (!form.budget && !form.roi_goal && !selectTimeStr.value) {
        proxy?.$modal.msgError('请至少填写一项需要更新的数据');
        return;
      }
      buttonLoading.value = true;
      let accountList;
      if (form.budget) {
        form.budget = Number(form.budget);
        form.budget_mode = 'BUDGET_MODE_DAY';
      }
      if (form.roi_goal) {
        form.roi_goal = Number(form.roi_goal);
        form.shop_platform = 'TB';
      }
      if (selectTimeStr.value) {
        form.schedule_time = selectTimeStr.value;
        form.schedule_scene = 'NEXT_DAY';
      }

      const data = {
        // advertiser_id: form.advertiser_id,
        advertiser_id: 1833527702547459, // 测试数据，正式使用时需要删除并使用上面的 advertiser_id
        ...(form.budget && { budget: form.budget }),
        ...(form.roi_goal && { roi_goal: form.roi_goal }),
        ...(form.schedule_time && { schedule_time: form.schedule_time })
      };
      proxy?.$modal.loading('');
      try {
        const res = await updateInfo(data);
        if (res.code != 0) {
          proxy?.$modal.msgError(res.message);
          return;
        }
        const result = getResultMsg(res.data);
        if (!result) {
          proxy?.$modal.msgSuccess('操作成功');
        } else {
          proxy?.$modal.msgWarning('' + result);
        }

        emit('update:visible', false);
        emit('refresh');
      } finally {
        buttonLoading.value = false;
        proxy?.$modal.closeLoading();
      }
    }
  });
};

const clearTime = () => {
  selectTimeStr.value = null;
  showSelectTimeStr.value = null;
  form.schedule_time = null;
};
const handelTimeSelect = () => {
  showTimeSelect.value = !showTimeSelect.value;
};

const getResultMsg = (result) => {
  let msg = '';
  if (result) {
    result.budget &&
      result.budget.map((item) => {
        if (item.code != 0) {
          msg += `项目：${item.project_id} ${item.error_message}`;
        }
      });
    result.week_schedule &&
      result.week_schedule.map((item) => {
        if (item.code != 0) {
          msg += `项目：${item.project_id} ${item.error_message}`;
        }
      });
    result.roigoal &&
      result.roigoal.map((item) => {
        if (item.code != 0) {
          msg += `项目：${item.project_id} ${item.error_message}`;
        }
      });
  }
  return msg;
};
</script>

<style lang="scss" scoped>
::v-deep(.text-center .el-input__inner) {
  text-align: center !important;
}
</style>
